<template>
  <a-breadcrumb class="container-breadcrumb">
    <a-breadcrumb-item>
      <icon-apps />
    </a-breadcrumb-item>
    <a-breadcrumb-item v-for="item in levelList" :key="item.name">
      {{ item.meta?.title }}
    </a-breadcrumb-item>
  </a-breadcrumb>
</template>

<script lang="ts" setup>
  import { RouteLocationNormalized } from 'vue-router';

  import type { AppRouteRecordRaw } from '@/router/routes/types';
  import useAppStore from '@/store/modules/app';
  import { pathResolve } from '@/utils/router-helper';
  import { filter, treeToList } from '@/utils/tree';

  const { currentRoute } = useRouter();
  const appStore = useAppStore();
  const levelList = ref<AppRouteRecordRaw[]>([]);

  const filterBreadcrumb = (routes: AppRouteRecordRaw[], parentPath = '') => {
    const res: AppRouteRecordRaw[] = [];

    for (const route of routes) {
      const data: AppRouteRecordRaw = { ...route };
      data.path = pathResolve(parentPath, data.path);
      if (data.children && data.children.length) {
        data.children = filterBreadcrumb(data.children, data.path);
      }
      if (data) {
        res.push(data);
      }
    }
    return res;
  };

  const menuRouters = computed(() => {
    const routers = appStore.serverMenu;
    return filterBreadcrumb(routers as AppRouteRecordRaw[]);
  });

  const getBreadcrumb = () => {
    const currentPath = currentRoute.value.matched.slice(-1)[0].path;
    const res = filter<AppRouteRecordRaw>(
      unref(menuRouters),
      (node: AppRouteRecordRaw) => {
        return node.path === currentPath;
      }
    );
    levelList.value = treeToList(res);
  };

  watch(
    () => currentRoute.value,
    (route: RouteLocationNormalized) => {
      if (route.path.startsWith('/redirect/')) {
        return;
      }
      getBreadcrumb();
    },
    {
      immediate: true,
    }
  );
</script>

<style scoped lang="less">
  .container-breadcrumb {
    margin-bottom: 16px;

    :deep(.arco-breadcrumb-item) {
      color: rgb(var(--gray-6));

      &:last-child {
        color: rgb(var(--gray-8));
      }
    }
  }
</style>
